package com.manga.mangaxmlparsing;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XMLParse {

	public XMLParse() {
		// TODO Auto-generated constructor stub
	}
	
	/**
	 * Getting XML from URL making HTTP request
	 * @param url string
	 * */
	public String getXMLFromUrl(String url){
		
		String xml =null;
		
		//defaultHttpClient
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		
		HttpResponse httpRespone;
		try {
			httpRespone = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpRespone.getEntity();
			xml = EntityUtils.toString(httpEntity);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// return XML
		return xml;
	}
	
	/**
	 * Getting XML DOM element
	 * @param xml string
	 * */
	public Document getDomElement(String xml){
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		Document doc = null;
		
		try {
			DocumentBuilder db = dbf.newDocumentBuilder();
			
			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(xml));
			
			doc = db.parse(is);
			
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return doc;
	}
	
	/**
	 * Getting node value
	 * @param element Node
	 * */
	public final String getElementValue(Node element){
		Node child = null;
		if (element.hasChildNodes()) {
			for (child = element.getFirstChild(); child!=null; child = child.getNextSibling()) {
				if (child.getNodeType()==Node.TEXT_NODE) {
					return child.getNodeValue();
				}
			}
		}
		
		return "";
	}
	
	 /**
	  * Getting node value
	  * @param Element node
	  * @param key string
	  * */
	 public String getValue(Element Manga, String str) {		
			NodeList n = Manga.getElementsByTagName(str);		
			return this.getElementValue(n.item(0));
		}
}
